package com.mashibing.service.impl.zookeeperImpl;

import com.mashibing.internalcommon.constant.CommonStatusEnum;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.request.DriverGrabRequest;
import com.mashibing.service.GrabService;
import com.mashibing.service.OrderService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service("GrabByZookeeperCuratorService")
public class GrabByZookeeperCuratorServiceImpl implements GrabService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CuratorFramework curatorFramework;

    @Override
    public ResponseResult grab(DriverGrabRequest driverGrabRequest) {
        ResponseResult responseResult = null;

        String orderIdKey = driverGrabRequest.getOrderId() + "";
        String parentNode = "/order-" + orderIdKey;

        InterProcessMutex lock = new InterProcessMutex(curatorFramework, parentNode);

        try {
            if (lock.acquire(10, TimeUnit.SECONDS)) {
                System.out.println("开始锁 zookeeper curator");
                responseResult = orderService.driverGrab(driverGrabRequest);
                System.out.println("结束锁 zookeeper curator");
            } else {
                responseResult = ResponseResult.fail(CommonStatusEnum.ORDER_CAN_NOT_GRAB.getCode(), CommonStatusEnum.ORDER_CAN_NOT_GRAB.getMessage(), null);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                lock.release();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return responseResult;
    }


}
